
const http = require('http')
const methods = require('methods') // 第三方模块 包含所有的请求方式 
const Router = require('./router/index')

function Application() {
}

Application.prototype.lazy_router = function () {
    if (!this._routers) {
        this._routers = new Router()
    }
}
Application.prototype.Router = Router

Application.prototype.route = function (...args) {
    this._routers.route(...args)
}
Application.prototype.use = function (...args) {
    this.lazy_router()
    this._routers.use(...args)
}

methods.forEach(method => {
    Application.prototype[method] = function (path, ...handlers) {
        this.lazy_router()
        this._routers[method](path, ...handlers)
    }
})


Application.prototype.param = function () { // 参数处理
    this.lazy_router()
    this._routers.param(...arguments)
}

Application.prototype.listen = function (port, cb) {
    this.lazy_router()
    const server = http.createServer((req, res) => {
        const done = () => {
            res.end(`Cannot ${req.method} ${req.url}`)
        }
        this._routers.handle(req, res, done)
    })
    server.listen(port, cb)
}
module.exports = Application 